{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import os\n",
    "import tempfile\n",
    "import tensorflow as tf\n",
    "import keras\n",
    "from keras import backend as K\n",
    "from keras import layers\n",
    "from PIL import Image\n",
    "import tensorflow as tf\n",
    "if K.backend() != 'tensorflow':\n",
    "    raise RuntimeError('This example can only run with the TensorFlow backend,'\n",
    "                       ' because it requires the Datset API, which is not'\n",
    "                       ' supported on other platforms.')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [],
   "source": [
    "import tensorflow as tf\n",
    "import scipy.io as sio\n",
    "import numpy as np\n",
    "import os\n",
    "from PIL import Image\n",
    "\n",
    "BASE_PATH=\"../../../Dataset/miml-image-data/original\"\n",
    "# BASE_PATH=r\"E:\\miml-image-data\\original\"\n",
    "# BASE_LABEL_PATH = r\"E:\\miml-image-data\\processed\"\n",
    "BASE_LABEL_PATH = \"../../../Dataset/miml-image-data/processed\"\n",
    "\n",
    "def mat2txt():\n",
    "    #使用scopy读取mat文件\n",
    "    mat_data = sio.loadmat(BASE_LABEL_PATH+\"/miml data.mat\")\n",
    "    #标签数据存储在targets中\n",
    "    label_data = mat_data['targets']\n",
    "    with open(BASE_LABEL_PATH+\"/label.txt\",'w') as f:\n",
    "        labels = []\n",
    "        for i in range(len(label_data)):\n",
    "            labels.append(label_data[i].tolist())\n",
    "        for j in range(len(labels[0])):\n",
    "            line = []\n",
    "            line.append(labels[0][i])\n",
    "            line.append(labels[1][i])\n",
    "            line.append(labels[2][i])\n",
    "            line.append(labels[3][i])\n",
    "            line.append(labels[4][i])\n",
    "            line = ','.join(str(s) for s in line)\n",
    "            jpg_name = str(j+1)+\".jpg\"\n",
    "            f.write(jpg_name + ','+line+'\\n')\n",
    "\n",
    "\n",
    "mat2txt()\n",
    "\n",
    "train_list = []\n",
    "test_list = []\n",
    "\n",
    "with open(BASE_LABEL_PATH+\"/label.txt\") as f:\n",
    "    i = 1\n",
    "    for line in f.readlines():\n",
    "        #print(line)\n",
    "        if i % 5 == 0:\n",
    "            test_list.append(line)\n",
    "        else:\n",
    "            train_list.append(line)\n",
    "        i += 1\n",
    "\n",
    "np.random.shuffle(train_list)\n",
    "np.random.shuffle(test_list)\n",
    "\n",
    "def int_2_one_hot(labels):\n",
    "    r = []\n",
    "    if labels[0] == -1:\n",
    "        r.append([0,0,0,0,0])\n",
    "    else:\n",
    "        r.append([1,0,0,0,0])\n",
    "\n",
    "    if labels[1] == -1:\n",
    "        r.append([0,0,0,0,0])\n",
    "    else:\n",
    "        r.append([0,1,0,0,0])\n",
    "\n",
    "    if labels[2] == -1:\n",
    "        r.append([0,0,0,0,0])\n",
    "    else:\n",
    "        r.append([0,0,1,0,0])\n",
    "\n",
    "    if labels[3] == -1:\n",
    "        r.append([0,0,0,0,0])\n",
    "    else:\n",
    "        r.append([0,0,0,1,0])\n",
    "\n",
    "    if labels[4] == -1:\n",
    "        r.append([0,0,0,0,0])\n",
    "    else:\n",
    "        r.append([0,0,0,0,1])\n",
    "    return r"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [],
   "source": [
    "def image_2_tfrecords(list,tf_record_path):\n",
    "    tf_write = tf.python_io.TFRecordWriter(tf_record_path)\n",
    "    for i in range(len(list)):\n",
    "        item = list[i]\n",
    "        item = item.strip('\\n')\n",
    "        items = item.split(',')\n",
    "        image_name = items[0]\n",
    "        image_path = os.path.join(BASE_PATH,image_name)\n",
    "        if os.path.isfile(image_path):\n",
    "            image = Image.open(image_path)\n",
    "            image = image.resize((224,224))\n",
    "            image = image.tobytes()\n",
    "            features ={}\n",
    "            features['raw_image'] = tf.train.Feature(bytes_list=tf.train.BytesList(value=[image]))\n",
    "            labels = int_2_one_hot(items[1:])\n",
    "            features['label_1'] = tf.train.Feature(int64_list=tf.train.Int64List(value=labels[0]))\n",
    "            features['label_2'] = tf.train.Feature(int64_list=tf.train.Int64List(value=labels[1]))\n",
    "            features['label_3'] = tf.train.Feature(int64_list=tf.train.Int64List(value=labels[2]))\n",
    "            features['label_4'] = tf.train.Feature(int64_list=tf.train.Int64List(value=labels[3]))\n",
    "            features['label_5'] = tf.train.Feature(int64_list=tf.train.Int64List(value=labels[4]))\n",
    "            tf_features = tf.train.Features(feature=features)\n",
    "            example = tf.train.Example(features=tf_features)\n",
    "            tf_serialized = example.SerializeToString()\n",
    "            tf_write.write(tf_serialized)\n",
    "        else:\n",
    "            print(\"not\")\n",
    "    tf_write.close()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [],
   "source": [
    "image_2_tfrecords(train_list,\"../../../Dataset/miml-image-data/processed/train.tfrecords\")\n",
    "image_2_tfrecords(test_list,\"../../../Dataset/miml-image-data/processed/test.tfrecords\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.4"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
